package shoooter.save;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;


public final class HighscoreManager {
    private static final String dataFolder = System.getenv("APPDATA");

    /**
     * 
     * @param score current game score
     * @return true if the method update the highscore, false otherwise
     */
    public static boolean  manageHighscore (int score) {
        BufferedReader reader;
        int hs;
        
        try {
            reader = new BufferedReader (new FileReader(new File (dataFolder+"/ShHs.txt")));
            try {
                hs = Integer.parseInt(reader.readLine());
                if (hs < score) {
                    saveHighscore(score);
                    return true;
                }
            } catch (IOException ex) {
                System.err.println(ex.getMessage());
                saveHighscore(score);
            } catch (NumberFormatException nfe) {
                System.err.println(nfe.getMessage());
                saveHighscore(score);
            }
        } catch (FileNotFoundException ex) {
           saveHighscore(score);
        }
        return false;
    }

    
    private static void saveHighscore (int h) {
        PrintStream outFile;
        try {
            outFile = new PrintStream(new FileOutputStream(dataFolder+"/ShHs.txt"));
            outFile.println(h);
            outFile.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(HighscoreManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static String getHighscore () {
        BufferedReader reader;
        Integer hs;
        
        try {
            reader = new BufferedReader (new FileReader(new File (dataFolder+"/ShHs.txt")));
            try {
                hs = Integer.parseInt(reader.readLine()); // cosi' sono sicuro che ho letto un intero
                return hs.toString();
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            } catch (NumberFormatException nfe) {
                System.err.println(nfe.getMessage());
            }
        } catch (FileNotFoundException fnf) {
           System.err.println(fnf.getMessage());
        }
        return "No highscore yet!";
    }
    
}
